package cn.xiaobai.captcha.handler.dbtype;

import cn.xiaobai.captcha.config.CaptchaProperties;
import cn.xiaobai.captcha.domain.CaptchaBean;
import cn.xiaobai.captcha.server.CaptchaServer;
import cn.xiaobai.captcha.utils.ConcurrentHashMapCacheUtils;
import cn.xiaobai.captcha.utils.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;
import java.util.List;

/**
 * mysql 类型处理器
 *
 * @author yangdaji
 * @version 1.0
 * @Description: 各种数据库缓存
 * @date 22-3-7 下午 11:06
 */
@Slf4j
public class MysqlAbstractTypeHandler extends AbstractDBAbstractTypeHandler {

    {
        log.info("mysql 缓存处理器");
    }

    public MysqlAbstractTypeHandler() {

    }

    public MysqlAbstractTypeHandler(CaptchaProperties captchaProperties) {
        super(captchaProperties);
    }

    @Autowired
    private CaptchaServer captchaServer;


    @Override
    public Boolean captchaCache(String key, String value) {
        log.info("使用 mysql 存储");
        CaptchaBean captchaBean = new CaptchaBean();
        captchaBean.setKey_name(key).setValue(value).setCacheTime(DateUtils.intervalToDate(new Date(), this.getExpire(), this.getTimeUnit()));
        return captchaServer.saveOrUpdateExpire(captchaBean, this.getExpire(), this.getTimeUnit());
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        log.info("加载缓存");
        List<CaptchaBean> captchaBeanList = captchaServer.list();
        captchaBeanList.forEach(v -> ConcurrentHashMapCacheUtils.setCache(v.getKey_name(), v));
        captchaServer.handExpiredData();
    }
}
